package bar.dark.lee.macro;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.SuperInterface;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.insert.InsertOutActivity;

public class MacroListActivity extends SuperActivity implements SuperInterface
{
	public static final String FROM = "from";
	
	public static final int REQUEST_MACRO_ADD = 0;
	public static final String REQUEST_MACRO_STRING = "request_macro_string";
	public static final String REQUEST_MACRO_UPDATE = "request_macro_update";
	public static final String REQUEST_MACRO_DATA = "request_macro_data";
	
	public static final String MACRO_DATA = "macro_data";
	
	private DBSQLite dbSql;
	
	private ListView listViewMacro;
	private Button btnAdd, btnInsert;
	
	private ArrayList<MacroData> macroList;
	private ArrayList<MacroData> tempMacroList;
	
	private int inMoneyColor;
	private int outMoneyColor;
	private int postMoneyColor;
	private int cashDrawingColor;
	
	private View resultView;
	
	private String [] checks;
	
	private String [] tempChecks; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.macro_list_activity);
		
		dbSql = DBSQLite.getInstance(superContext);
		
		setTitle("빠른 입력");
		setGoneTipButton();
		
		setFindView();
		setClickListener();
	}
	
	@Override
	protected void onResume() 
	{
		super.onResume();
		
		new ShowDialog().execute(BDUtil.asyncFlag, 0);
	}
	
	@Override
	public void setFindView() 
	{
		listViewMacro = (ListView)findViewById(R.id.macroListView);
		btnAdd = (Button)findViewById(R.id.macroListAddButton);
		btnInsert = (Button)findViewById(R.id.macroListInsertButton);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		
		inMoneyColor = getResources().getColor(R.color.inmoney);
		outMoneyColor = getResources().getColor(R.color.outmoney);
		postMoneyColor = getResources().getColor(R.color.postmoney);
		cashDrawingColor = getResources().getColor(R.color.cashdrawingmoney);
	}

	@Override
	public void setDataSetting() {
		
		macroList = new ArrayList<MacroData>();

		String query = "SELECT * from macro_list;";
		
		tempChecks = new String[0];
		
		dbSql.selectMapTile(superContext, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				c.moveToFirst();
				
				tempChecks = new String[count];
				
				if (count != 0)
				{
					int idIndex = c.getColumnIndex("id");
					int typeIndex = c.getColumnIndex("type");
					int titleIndex = c.getColumnIndex("title");
					int inMoneyIndex = c.getColumnIndex("inmoney");
					int outMoneyIndex = c.getColumnIndex("outmoney");
					int postMoneyIndex = c.getColumnIndex("postmoney");
					int checkIndex = c.getColumnIndex("checkbox");
					int categoryIndex = c.getColumnIndex("category");
					int memoIndex = c.getColumnIndex("memo");
					int linkidIndex = c.getColumnIndex("linkid");
					int moneykindIndex = c.getColumnIndex("moneykind");
					int postmoneykindIndex = c.getColumnIndex("postmoneykind");
					int linktypeIndex = c.getColumnIndex("linktype");
					int deleteynIndex = c.getColumnIndex("deleteyn");
					
					for (int i = 0; i < count; i++)
					{
						MacroData data = new MacroData();
						data.setId(c.getInt(idIndex) + "");
						data.setType(c.getString(typeIndex));
						data.setTitle(c.getString(titleIndex));
						data.setInmoney(c.getString(inMoneyIndex));
						data.setOutmoney(c.getString(outMoneyIndex));
						data.setPostmoney(c.getString(postMoneyIndex));
						data.setCheck(c.getString(checkIndex));
						data.setId(c.getString(idIndex));
						data.setCategory(c.getString(categoryIndex));
						data.setMemo(c.getString(memoIndex));
						data.setLinkid(c.getString(linkidIndex));
						data.setMoneykind(c.getString(moneykindIndex));
						data.setPostmoneykind(c.getString(postmoneykindIndex));
						data.setLinktype(c.getString(linktypeIndex));
						data.setDeleteyn(c.getString(deleteynIndex));
						
						tempChecks[i] = data.getCheck();
						
						macroList.add(data);
						
						c.moveToNext();
					}
				}
			}
		});
	}

	@Override
	public void setClickListener() {
		
		btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(superContext, InsertOutActivity.class);
				intent.putExtra(FROM, REQUEST_MACRO_STRING);
				startActivity(intent);
			}
		});
		
		btnInsert.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
	}
	
//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
//		
//		if (requestCode == REQUEST_MACRO_ADD)
//		{
//			if (resultCode == RESULT_OK)
//			{
//				new ShowDialog().execute(BDUtil.asyncFlag, 0);
//			}
//		}
//	}
	
	@Override
	public void onBackPressed() 
	{
		new ShowDialog().execute(BDUtil.asyncFlag, 2);
	}
	
	private void saveMacroCheck()
	{
		for (int i=0; i<macroList.size(); i++)
		{
			MacroData macroData = macroList.get(i);
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (checks[i].equals("1"))
			{
				map.put("checkbox", "1");
			}
			else
			{
				map.put("checkbox", "0");
			}
			
			String [] whereArgs = new String[]{macroData.getId() + ""};
			dbSql.update(superContext, "macro_list", map, "id = ?", whereArgs);
		}
	}
	
	private int linkId = -1;
	private boolean checkFlag = false;
	
	private void insertInOutTable()
	{
		checkFlag = false;
		
		for (int i=0; i<macroList.size(); i++)
		{
			final MacroData macroData = macroList.get(i);
			
			if (checks[i].equals("1"))
			{
				checkFlag = true;
				
				if (macroData.getType().equals(BDConstents.REAL_TYPE))
				{
					dbSql.selectMapTile(superContext, "SELECT money FROM real_money", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(macroData.getOutmoney()));
							int moneyIndex = c.getColumnIndex("money");
							
							c.moveToFirst();
							
							BigDecimal money = BigDecimal.ZERO;
							for (int i = 0; i < c.getCount(); i++)
							{
								money = money.add(new BigDecimal(c.getString(moneyIndex)));
							}
							
							money = money.subtract(tempMoney);
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("money", money.toString());
							dbSql.update(superContext, "real_money", map, null, null);
						}
					});
				}
				else if (macroData.getType().equals(BDConstents.BANK_TYPE))
				{
					dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE name = '" 
							+ BDUtil.getApostrophe(macroData.getMoneykind()) + "';", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(macroData.getOutmoney()));
							
							int moneyIndex = c.getColumnIndex("money");
							
							c.moveToFirst();
							BigDecimal money = BigDecimal.ZERO;
							for (int i = 0; i < c.getCount(); i++)
							{
								money = money.add(new BigDecimal(c.getString(moneyIndex)));
								c.moveToNext();
							}
							
							money = money.subtract(tempMoney);
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("money", money.toString());
							String [] whereArgs = new String[]{macroData.getMoneykind()};
							dbSql.update(superContext, "bankbook", map, "name = ?", whereArgs);
						}
					});
				}
				else if (macroData.getType().equals(BDConstents.CHECK_TYPE))
				{
					dbSql.selectMapTile(superContext, "SELECT banklink FROM check_card WHERE name = '" 
							+ BDUtil.getApostrophe(macroData.getMoneykind()) + "';", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							linkId = -1;
							
							int banklinkIndex = c.getColumnIndex("banklink");
							
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								linkId = c.getInt(banklinkIndex);
								c.moveToNext();
							}
						}
					});
					
					if (linkId > -1)
					{
						dbSql.selectMapTile(superContext, "SELECT money FROM bankbook WHERE id = " + linkId + ";", new ParseSelectData()
						{
							@Override
							public void resultData(Cursor c)
							{
								BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(macroData.getOutmoney()));
								
								int moneyIndex = c.getColumnIndex("money");
								
								c.moveToFirst();
								BigDecimal money = BigDecimal.ZERO;
								for (int i = 0; i < c.getCount(); i++)
								{
									money = money.add(new BigDecimal(c.getString(moneyIndex)));
									c.moveToNext();
								}
								
								money = money.subtract(tempMoney);
								
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("money", money.toString());
								String [] whereArgs = new String[]{linkId + ""};
								dbSql.update(superContext, "bankbook", map, "id = ?", whereArgs);
							}
						});
					}
				}
				else if (macroData.getType().equals(BDConstents.CREDIT_TYPE))
				{
					dbSql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '" 
							+ BDUtil.getApostrophe(macroData.getMoneykind()) + "';", new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(macroData.getPostmoney()));
							int id = -1;
							int idIndex = c.getColumnIndex("id");
							int moneyIndex = c.getColumnIndex("outmoney");
							
							c.moveToFirst();
							BigDecimal money = BigDecimal.ZERO;
							for (int i = 0; i < c.getCount(); i++)
							{
								id = c.getInt(idIndex);
								money = money.add(new BigDecimal(c.getString(moneyIndex)));
								c.moveToNext();
							}
							
							money = money.add(tempMoney);
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("outmoney", money.toString());
							String [] whereArgs = new String[]{id + ""};
							dbSql.update(superContext, "credit_card", map, "id = ?", whereArgs);
						}
					});
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("category", macroData.getCategory());
				
				if (macroData.getType().equals("3"))
				{
					map.put("postmoney", BDUtil.getCommaDel(macroData.getPostmoney()));
				}
				else
				{
					map.put("outmoney", BDUtil.getCommaDel(macroData.getOutmoney()));
				}
				
				Calendar calendar = Calendar.getInstance();
				String date = BDUtil.getDateDB(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH));
				map.put("date", date);
				
				map.put("moneykind", macroData.getMoneykind());
				map.put("type", macroData.getType());
				
				map.put("memo", macroData.getMemo());
				
				dbSql.insert(this, map, "in_out");
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setBalance(macroData.getType(), macroData.getMoneykind());
				
				map.clear();
				map.put("checkbox", "1");
				String [] whereArgs = new String[]{macroData.getId() + ""};
				dbSql.update(superContext, "macro_list", map, "id = ?", whereArgs);
			}
			else
			{
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("checkbox", "0");
				String [] whereArgs = new String[]{macroData.getId() + ""};
				dbSql.update(superContext, "macro_list", map, "id = ?", whereArgs);
			}
		}
	}
	
	private class MacroAdapter extends ArrayAdapter<MacroData>
	{
		Context context;
		int textViewId;
		ArrayList<MacroData> list;

		public MacroAdapter(Context context, int textViewResourceId, ArrayList<MacroData> list) 
		{
			super(context, textViewResourceId, list);
			
			this.context = context;
			this.textViewId = textViewResourceId;
			this.list = list;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v  = li.inflate(textViewId, null);
			}
			
			MacroData data = list.get(position);
			
			TextView textType = (TextView)v.findViewById(R.id.macroListItem_textType);
			TextView textTitle = (TextView)v.findViewById(R.id.macroListItem_textTitle);
			TextView textMoney = (TextView)v.findViewById(R.id.macroListItem_textMoney);
			CheckBox checkBox = (CheckBox)v.findViewById(R.id.macroListItem_checkbox);
			
			if (data.getType().equals(BDConstents.REAL_TYPE))
			{
				textType.setText(BDConstents.REAL_MONEY);
			}
			else if (data.getType().equals(BDConstents.BANK_TYPE))
			{
				textType.setText(BDConstents.BANK_MONEY);
			}
			else if (data.getType().equals(BDConstents.CHECK_TYPE))
			{
				textType.setText(BDConstents.CHECK_CARD);
			}
			else if (data.getType().equals(BDConstents.CREDIT_TYPE))
			{
				textType.setText(BDConstents.CREDIT_CARD);
			}
			
			textTitle.setText(data.getTitle());
			
			if (data.getType().equals(BDConstents.CREDIT_TYPE))
			{
				textMoney.setText("-" + BDUtil.getWon(data.getPostmoney()));
				textMoney.setTextColor(postMoneyColor);
			}
			else if (data.getInmoney().equals("0"))
			{
				textMoney.setText("-" + BDUtil.getWon(data.getOutmoney()));
				textMoney.setTextColor(outMoneyColor);
			}
			else
			{
				textMoney.setText("+" + BDUtil.getWon(data.getInmoney()));
				textMoney.setTextColor(inMoneyColor);
			}
			 
			if (checks[position].equals("1"))
			{
				checkBox.setChecked(true);
			}
			else
			{
				checkBox.setChecked(false);
			}
		
			checkBox.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) 
				{
					CheckBox cb = (CheckBox) v;
					
					if (cb.isChecked()) 
					{
						checks[position] = "1";
					}
					else
					{
						checks[position] = "0";
					}
				}
			});
			
			return v;
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			MacroData data = macroList.get(pos);
			
			Intent intent = new Intent(superContext, InsertOutActivity.class);
			intent.putExtra(FROM, REQUEST_MACRO_UPDATE);
			intent.putExtra(MACRO_DATA, data);
			startActivity(intent);
		}
	};
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 0)
				{
					setDataSetting();
					
					return arg0[1];
				}
				else if (arg0[1] == 1)
				{
					try
					{
						dbSql.beginTansaction(superContext);
						
						insertInOutTable();
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							dbSql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						dbSql.beginTansaction(superContext);
						
						saveMacroCheck();
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return arg0[1];
					} finally {
						try 
						{
							dbSql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return arg0[1];
						}
					}
					
					return arg0[1];
				}
				
				return -1;
			}
			else
			{
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.showDialog(superContext, "오류", "데이터를 가져오는데 실패 하였습니다.");
			}
			else if (result == 0) 
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				checks = new String[tempChecks.length];
				
				for (int i = 0; i < tempChecks.length; i++) 
				{
					checks[i] = tempChecks[i];
				}
				
				if (listViewMacro.getFooterViewsCount() > 0)
				{
					listViewMacro.removeFooterView(resultView);
				}
				
				if (macroList.size() < 1)
				{
					listViewMacro.addFooterView(resultView);
					listViewMacro.setFooterDividersEnabled(false);
					listViewMacro.setOnItemClickListener(null);
				}
				else
				{
					listViewMacro.setSelected(true);
					listViewMacro.setOnItemClickListener(onItemClickListener);
					listViewMacro.setFooterDividersEnabled(true);
				}
				
				MacroAdapter adapter = new MacroAdapter(superContext, R.layout.macro_list_item, macroList);
				listViewMacro.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
			else if (result == 1)
			{
				if (checkFlag)
				{
					BDUtil.showDialogFinish(superContext, "입력완료", "선택하신 빠른입력 항목들을 가계부에 입력했습니다.");
				}
				else 
				{
					BDUtil.showDialog(superContext, "입력실패", "하나 이상의 항목을 선택해주세요.");
				}
			}
			else if (result == 2)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				finish();
			}
		}
	}
	
	@Override
	protected void tipButton() {
	}
}
